package com.software.car.secutiry;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.software.car.api.UserService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.utils.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description
 * @Author 魔法はまだ解けない
 * @Date 2021/1/17
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserService userService;

    @Bean
    PasswordEncoder passwordWordEncode(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/public/**","/**/public/**","/test/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
//                .loginPage("/test/login")
//                配置登录post请求地址
//                .loginProcessingUrl("/public/web/login")
                .successHandler((request,response,authentication)->{
                    //配置登陆成功
                    logger.info("登陆成功！！");
                })
                .permitAll()
                .failureHandler((request,response,authentication)->{
                    //配置登陆失败
                    logger.info("登录失败！！");
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((request,response,authentication)->{
                    //登出
                    logger.info("登出成功！！");
                })
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request,response,exception)->{
                    //异常拦截
                    sendMessage(response, CommonResult.fail(ResultEnum.LOGIN_ERROR));
                })
                .and()
                .cors()
                .and()
                .csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(new JwtRequestFilter(userService), UsernamePasswordAuthenticationFilter.class);
    }

    public static void sendMessage(HttpServletResponse response, CommonResult commonResult) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(commonResult));
        writer.flush();
        writer.close();
    }

}
